package com.eastcom.bm.dataprocess.processor;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.eastcom.canicula.stope.utils.MyLogger;
import com.eastcom.common.db.Session;
import com.eastcom.common.db.SessionFactory;


public class RealTimeParamHelper {

    private static boolean storeHistory=false;
	
	private static PreparedStatement psta=null;
	
	private static Connection con=null;
	
	private static Session session=null;
	
	private static boolean isClosed=false;
	
	static{
		initial();
	}
	
	private static void initial(){
		try {
			session=SessionFactory.getInstance().getSession();
			con=session.getConnection();
		} 
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static void destory(){
		if(psta!=null){
			try {
				psta.close();
			} 
		    catch (Exception e) {}
		    
		    psta=null;
		}
		
		SessionFactory.getInstance().closeSession();
	}
	
	public static void close(){
		if(!isClosed){
			destory();
			isClosed=true;
		}
	}
	
	public static Map querySqmRawValueAndTime(String sql,String dataSetId,String demension,String indicatorUUID,String startDate){
		
		ResultSet rs=null;
		try{
			psta=psta==null?con.prepareStatement(sql):psta;
			psta.setString(1, dataSetId);
			psta.setString(2, demension);
			psta.setString(3, indicatorUUID);
			psta.setString(4, startDate);
			rs=psta.executeQuery();
		}
		catch(Exception e){
			MyLogger.logger.error("RedirectProcessor query history data error", e);
			System.out.println("querySqmRawValueAndTime error "+e.getMessage());
			destory();
			initial();
		}
		
		if(rs!=null){
			try{		
				int count=1;
				HashMap dataMap = new HashMap();		
				HashMap timeStampUpdateTimeMap = new HashMap();
				Map timeStampHistory= new HashMap();
				dataMap.put("TIMESTAMP_HISTORY", timeStampHistory);
				
				while (rs.next()) {						
					String time_stamp = rs.getString(1);
					int pointIndex=time_stamp.lastIndexOf(".");
					time_stamp=time_stamp.substring(0, pointIndex==-1?time_stamp.length():time_stamp.lastIndexOf("."));
					long update_time = rs.getBigDecimal(2).longValue();

					if (timeStampUpdateTimeMap.containsKey(time_stamp)) {
						if (Long.parseLong((String)timeStampUpdateTimeMap.get(time_stamp))>=update_time)
							continue;
					}

					timeStampUpdateTimeMap.put(time_stamp, String.valueOf(update_time));							                	               			

					String value=rs.getBigDecimal(4)==null?"0":rs.getBigDecimal(4).toString();
					if(storeHistory){
					    dataMap.put(time_stamp, value);
					    dataMap.put(count, time_stamp);
					}
					
					String hourMinute=time_stamp.substring(time_stamp.indexOf(" ")+1, time_stamp.lastIndexOf(":"));
					Map timeStampMap=(Map)timeStampHistory.get(hourMinute);

					if(timeStampMap==null){
						timeStampMap=new HashMap();
						timeStampHistory.put(hourMinute, timeStampMap);
					}
					timeStampMap.put(time_stamp.substring(0, time_stamp.indexOf(" ")), value);
					
					count++;
				}

				return dataMap;
			
			}
			catch(Exception e){
				MyLogger.logger.error("querySqmRawValueAndTime error",e);
				System.out.println("querySqmRawValueAndTime error: "+e.getMessage());
			}
			
			finally{
				if(rs!=null)
					try {
						rs.close();
					} 
				    catch (Exception e) {}
			}
		}
	
		return null;
		
	}
	
	public static void main(String []args){
		
		String sql="select TIME_STAMP,UPDATE_TIME,DIMENSION,HOUR,MINUTE,VALUE from SQM_RAW_DATA " +
       		                    "where DIMENSION='GZSGSN201BEr' and INDICATOR_UUID ='gprs_pdp_succ_ratio' " +
       				            "and GRANULARITY=3600 and TIME_STAMP >=to_date('2010-8-11 0:00:00', 'yyyy-mm-dd hh24:mi:ss') AND SMOOTH_FLAG=0 ORDER BY TIME_STAMP asc,UPDATE_TIME desc";
		Map map=querySqmRawValueAndTime(sql,"","","","");
		Map map1=(Map) map.remove("TIMESTAMP_HISTORY");
		System.out.println(map.keySet());

		Iterator it=map1.values().iterator();
		while(it.hasNext())
			System.out.println(it.next());
		System.gc();
	}
	
}
